import { getDictMap } from '@/api/setting/dict'; // 请求字典接口
import { isArray, isString } from '@/utils';

/**
 * @description:获取字典列表
 * @param {Object} options 配置项
 * @param {Object=} options.initData 初始值
 * @param {String|Array} options.groupCodes -字典组名(支持逗号分隔的字符串或者数组)
 * @param {Boolean=} options.manual -是否手动执行
 * @param {Function=} options.onSuccess -成功回调
 * @param {Function=} options.onError -失败回调
 * @return {Object}
 */
export function useDictMap(options = {}) {
  const { initData = {}, groupCodes = '', manual = false, onSuccess = () => {}, onError = console.error } = options;
  let groupCodeList = [];
  let groupCodeStr = '';
  if (isArray(groupCodes)) {
    groupCodeList = [...groupCodes];
    groupCodeStr = groupCodes.join(',');
  }
  if (isString(groupCodes)) {
    groupCodeList = groupCodes.split(',');
    groupCodeStr = groupCodes;
  }
  const state = reactive({
    data: initData,
    error: null
  });
  const run = async () => {
    try {
      const { data, code } = await getDictMap({
        groupCodes: groupCodeStr
      });
      if (code === 200) {
        onSuccess();
        groupCodeList.forEach((item) => {
          state.data[item] = data[item].map((m) => {
            return { value: m.dicCode, label: m.dicName };
          });
        });
        console.log('data', state);
      }
    } catch (error) {
      groupCodeList.forEach((item) => {
        state.data[item] = [];
      });
      onError();
      state.error = error;
    }
  };
  onMounted(() => {
    if (!manual) {
      run();
    }
  });
  return {
    ...toRefs(state),
    run
  };
}
